package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.bean.TalkPerson;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.utils.CommonUtils;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.swipeitemlayout.BGASwipeItemLayout;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * Fragment-话题成员管理
 */
public class ProTalkManageMemberFragment extends Fragment implements AYSwipeRecyclerView.OnRefreshLoadListener {
    public final static int TYPE_JOIN = 0;
    public final static int TYPE_BROWSE = 1;

    private static String ARG_PARAM_TYPE = "ARG_PARAM_TYPE";
    private static String ARG_PARAM_TALKID = "ARG_PARAM_TALKID";

    Boolean initData = false;
    private int mType = 0;
    private String mTalkId;
    private ArrayList<TalkPerson> mData;
    private AYSwipeRecyclerView recycler;
    private ConversationAdapter mAdapter;
    private EditText et_search;
    private TextView tv_num;

    public static Object newInstance(int type, String id) {
        ProTalkManageMemberFragment fragment = new ProTalkManageMemberFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM_TYPE, type);
        args.putSerializable(ARG_PARAM_TALKID, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mType = getArguments().getInt(ARG_PARAM_TYPE);
        mTalkId = getArguments().getString(ARG_PARAM_TALKID);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_talk_manager_member, container, false);
        recycler = view.findViewById(R.id.aySwipeRecyclerView);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData = true;

        mData = new ArrayList<>();
        recycler.setOnRefreshLoadLister(this);
        mAdapter = new ConversationAdapter(getActivity(), mType, mData);
        recycler.setAdapter(mAdapter);
        recycler.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        recycler.setEmptyView(View.inflate(getActivity(), R.layout.recycle_empty_pro_talk_member, null));

        et_search = getView().findViewById(R.id.et_search);
        tv_num = getView().findViewById(R.id.tv_num);
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    getList();
                    return true;
                }
                return false;
            }
        });
        getList();
    }

    @Override
    public void loadFirst() {
        getList();
    }

    @Override
    public void loadNext() {

    }


    class ConversationAdapter extends BaseRecyclerAdapter<ConversationAdapter.ItemViewHolder> {

        private Context context;
        private int type;

        public ConversationAdapter(Context context, int type, List<TalkPerson> mDataList) {
            this.context = context;
            this.type = type;
        }

        @NonNull
        @Override
        public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int type) {
            View v = LayoutInflater.from(context).inflate(R.layout.item_pro_talk_member_join, viewGroup, false);

            if (type == TYPE_BROWSE) {
                v.findViewById(R.id.btn_jinyan).setVisibility(View.GONE);
                v.findViewById(R.id.btn_divider).setVisibility(View.GONE);
            }

            return new ItemViewHolder(v);
        }

        @Override
        public void onBindViewHolder(final ItemViewHolder holder, final int position) {
            super.onBindViewHolder(holder, position);
            final TalkPerson person = mData.get(position);

            Glide.with(context).load(person.getAvatar())
                    .bitmapTransform(new CropCircleTransformation(context))
                    .placeholder(R.drawable.logo)
                    .into(holder.avatar);
            holder.tv_name.setText(person.getUsername());
            holder.tv_money.setText("确认金额：" + CommonUtils.resetMoney(person.getConfirmAmount()) + "元");
            if (person.isBanned()) {
                holder.tv_jinyan.setVisibility(View.VISIBLE);
            } else {
                holder.tv_jinyan.setVisibility(View.GONE);
            }

            if (person.isKindGuarantee()) {
                holder.tv_tag.setVisibility(View.VISIBLE);
                holder.tv_tag.setText("担保优先");
                holder.tv_tag.setBackgroundResource(R.drawable.bg_text_pro_talk_member_tag_dbyx);
            } else if (person.isKindTax()) {
                holder.tv_tag.setVisibility(View.VISIBLE);
                holder.tv_tag.setText("税务");
                holder.tv_tag.setBackgroundResource(R.drawable.bg_text_pro_talk_member_tag_sw);
            } else if (person.isKindOther()) {
                holder.tv_tag.setVisibility(View.VISIBLE);
                holder.tv_tag.setText("其他优先");
                holder.tv_tag.setBackgroundResource(R.drawable.bg_text_pro_talk_member_tag_qtyx);
            } else if (person.isKindOrdinary()) {
                holder.tv_tag.setVisibility(View.VISIBLE);
                holder.tv_tag.setText("普通");
                holder.tv_tag.setBackgroundResource(R.drawable.bg_text_pro_talk_member_tag_pt);
            } else {
                holder.tv_tag.setVisibility(View.GONE);
            }
            holder.btn_jinyan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bannedTalkMember(person);
                }
            });
            holder.btn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteTalkMember(person);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        @Override
        public int getItemViewType(int position) {
            return type;
        }

        class ItemViewHolder extends BaseHolder {

            public BGASwipeItemLayout silItemBgaswipeRoot;
            public View unreadCount;
            public  View btn_jinyan;
            public View btn_delete;
            public ImageView avatar;
            public TextView tv_name;
            public TextView tv_tag;
            public TextView tv_jinyan;
            public TextView tv_money;

            public ItemViewHolder(View view) {
                super(view);
                silItemBgaswipeRoot = view.findViewById(R.id.sil_item_bgaswipe_root);
                unreadCount = view.findViewById(R.id.unread_count);
                btn_jinyan = view.findViewById(R.id.btn_jinyan);
                btn_delete = view.findViewById(R.id.btn_delete);
                avatar = view.findViewById(R.id.avatarImageView);
                tv_name = view.findViewById(R.id.tv_name);
                tv_tag = view.findViewById(R.id.tv_tag);
                tv_jinyan = view.findViewById(R.id.tv_jinyan);
                tv_money = view.findViewById(R.id.tv_money);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_TALK_MEMBER)) {
            getList();
        }
    }


    private void getList() {
        String key = et_search.getText().toString().trim();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .getParticipantList(userToken, mTalkId, key, mType, 1, 400)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        JsonArray arr = data.getAsJsonArray("list");
                        List<TalkPerson> list = TalkPerson.parse(arr);
                        mData.clear();
                        mData.addAll(list);
                        recycler.onFinishRequest(false, false);

                        tv_num.setText("人数：" + mData.size() + "人");
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        recycler.onFinishRequest(true, false);
                    }
                });
    }

    private void deleteTalkMember(TalkPerson person) {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .deleteTalkMember(userToken, person.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        ToastUtil.showShort("删除成功");
                        getList();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private void bannedTalkMember(TalkPerson person) {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .bannedTalkReply(userToken, mTalkId, person.getCreditorId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        ToastUtil.showShort("操作成功");
                        getList();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

}
